<template>
  <view class="page">
    <!-- 姓名 start -->
    <view class="cu-form-group">
      <view class="title">{{i18n['真实姓名']}}</view>
      <input v-model="realName" :placeholder="i18n['请输入真实姓名']" />
    </view>
    <!-- 姓名 end -->

    <!-- 手机号 start -->
    <view class="cu-form-group">
      <view class="title">{{i18n['手机号码']}}</view>
      <input type="number" v-model="phone" :maxlength="11" :placeholder="i18n['请输入手机号']" />
      <view class="cu-capsule radius">
        <view class="cu-tag bg-blue"> +86 </view>
        <view class="cu-tag line-blue"> {{i18n['中国大陆']}} </view>
      </view>
    </view>
    <!-- 手机号 end -->

    <!-- 身份证号 start -->
    <view class="cu-form-group">
      <view class="title">{{i18n['身份证号']}}</view>
      <input type="number" v-model="cardID" :maxlength="18" :placeholder="i18n['请输入身份证号']" />
    </view>
    <!-- 身份证号 end -->

    <!-- 身份证正面（国徽面） start -->
    <view class="cu-bar bg-white margin-top">
      <view class="action"> {{i18n['身份证正面（国徽面）']}} </view>
    </view>
    <view class="cu-form-group">
      <view class="grid col-4 grid-square flex-sub">
        <view class="bg-img" v-if="frontPic != ''">
          <image :src="frontPic" mode="aspectFill"></image>
          <view class="cu-tag bg-red" @click="cardIDDelete(0)">
            <text class="cuIcon-close"></text>
          </view>
        </view>
        <view class="solids" v-if="frontPic == ''" @click="picCut(0)">
          <text class="cuIcon-cameraadd"></text>
        </view>
      </view>
    </view>
    <!-- 身份证正面（国徽面） end -->

    <!-- 身份证反面（头像面） start -->
    <view class="cu-bar bg-white margin-top">
      <view class="action"> {{i18n['身份证反面（头像面）']}} </view>
    </view>
    <view class="cu-form-group">
      <view class="grid col-4 grid-square flex-sub">
        <view class="bg-img" v-if="reversePic != ''">
          <image :src="reversePic" mode="aspectFill"></image>
          <view class="cu-tag bg-red" @click="cardIDDelete(1)">
            <text class="cuIcon-close"></text>
          </view>
        </view>
        <view class="solids" v-if="reversePic == ''" @click="picCut(1)">
          <text class="cuIcon-cameraadd"></text>
        </view>
      </view>
    </view>
    <!-- 身份证反面（头像面） end -->

    <!-- 提交按钮 start -->
    <view class="submit-btn" @click="submitInfo">
      <text class="text-xl text-white">{{i18n['提交']}}</text>
    </view>
    <!-- 提交按钮 end -->
  </view>
</template>

<script>
  import { UploadImage, validate } from "@/common/utils/index";
  export default {
    name: "Authentication",
    data() {
      return {
        realName: "",       // {String} 真实姓名
        phone: "",          // {Number} 手机号
        cardID: "",         // {Number} 身份证号
        reverseORfront: 0,  // {Number} 判断用户上传的是正面还是反面，（0：正面；1：反面；）
        reversePic: "",     // {String} 反面URL
        reverseID: "",      // {Number} 反面ID
        frontPic: "",       // {String} 正面URL
        frontID: "",        // {Number} 正面ID
      };
    },
    created() { },
    mounted() {
      /**
       * @function
       * @description 监听图片裁剪
       */
      uni.$on("uPicCropper", (path) => {
        console.log("监听到上传事件");
        this.uploadCardID(path);
      });
    },
    onLoad() { 
      this.setNavigationBarTitle(this.i18n['实名认证'])
    },
    onUnload() {
      /**
       * @function
       * @description 页面关闭时停止监听
       */
      uni.$off("uPicCropper");
    },
    computed: {},
    methods: {
      /**
       * @event
       * @description 提交信息
       * @property {Object} data - 请求借口的信息
       * @property {String} data.name - 用户真实姓名
       * @property {Number} data.mobile - 用户手机号
       * @property {Number} data.idcard_no - 用户身份证号
       * @property {Number} data.idcard_front - 身份证正面
       * @property {Number} data.idcard_reverse - 身份证反面
       * @property {Boolean} isPass - 用户的输入信息是否通过验证
       */
      async submitInfo() {
        let data = {
          name: this.realName,
          mobile: this.phone,
          idcard_no: this.cardID,
          idcard_front: this.frontID,
          idcard_reverse: this.reverseID,
          auth_type: 1   // 实名认证
        };
        let isPass = await this.dataExamine(this.realName, this.phone, this.cardID);
        if (!isPass && this.frontPic != '' && this.reversePic != '') {
          this.$api.post(global.apiUrls.postUserAuthentication, data)
            .then(res => {
              if (res.data.code == 1) {
                this.$message.info(this.i18n['提交申请成功'])
                setTimeout(() => {
                  this.$urouter.navigateBack();
                }, 500)
              } else {
                this.$message.info(res.data.msg);
              }
            })
        } else {
          if (isPass == 'phone') {
            this.$message.info(this.i18n['请输入正确的手机号码']);
            return false;
          }
          if (isPass == 'cardID') {
            this.$message.info(this.i18n['请输入正确的身份证号']);
            return false;
          }
          if (isPass == 'realName') {
            this.$message.info(this.i18n['请输入姓名']);
            return false;
          }
          if (!this.frontPic) {
            this.$message.info(this.i18n['请上传身份证正面']);
            return false;
          }
          if (!this.reversePic) {
            this.$message.info(this.i18n['请上传身份证反面']);
            return false;
          }
        }
      },
      /**
       * @event
       * @description 裁剪图片
       * @param {Object} type - 需要裁剪的图片信息
       */
      picCut(type) {
        this.reverseORfront = type;
        uni.chooseImage({
          count: 1,
          sizeType: ["original", "compressed"],
          sourceType: ["album", "camera"],
          success: (res) => {
            uni.navigateTo({
              url:
                '/pages/user/user/avatar-cropping/index?rectWidth=240&rectHeight=151&fileType="jpg"&myImgUrl=' +
                res.tempFilePaths[0],
              animationDuration: 0,
            });
          },
        });
      },
      /**
       * @event
       * @description 删除图片
       * @param {Object} type - 需要删除的图片信息
       */
      cardIDDelete(type) {
        switch (type) {
          case 0:
            this.frontPic = "";
            break;
          case 1:
            this.reversePic = "";
            break;
          default:
            break;
        }
      },
      /**
       * @function
       * @description 上传图片
       * @param {Object} data - 需要上传的图片信息
       */
      uploadCardID(data) {
        console.log("开始上传");
        uni.showLoading();
        let that = this;
        new UploadImage([data], {
          complete: (res) => {
            uni.hideLoading();
            switch (that.reverseORfront) {
              case 0:
                that.frontPic = res[0].path;
                that.frontID = res[0].id;
                break;
              case 1:
                that.reversePic = res[0].path;
                that.reverseID = res[0].id;
                break;
              default:
                break;
            }
          },
        });
      },
      /**
       * @function
       * @description 参数检验
       * @param {String} realName - 用户真实姓名
       * @param {Number} phone - 手机号
       * @param {Number} cardID - 身份证号
       */
      dataExamine(realName, phone, cardID) {
        console.log('检验结果', !validate(realName, "require"), !validate(phone, "phone"), !validate(cardID, "idcard"))
        if (!validate(realName, "require")) {
          return 'realName'
        } else if (!validate(phone, "phone")) {
          return 'phone'
        } else if (!validate(cardID, "idcard")) {
          return 'cardID'
        }
        else {
          return false;
        }
      },
    },
  };
</script>

<style lang="scss" scoped>
  page {
    background: #fff;
  }

  .page {
    height: calc(100vh - 88rpx);
  }

  .submit-btn {
    position: fixed;
    bottom: 88rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 80%;
    height: 88rpx;
    border-radius: 44rpx;
    background: $theme;
    text-align: center;
    line-height: 88rpx;
  }
</style>